<?php
/**
 * ws 优化基础类库
 *
 * 面向对象
 */
class Ws {
    const HOST = "0.0.0.0";
    const PORT = 8812;
    public $ws = null;

    public function __construct()
    {
        $this->ws = new swoole_websocket_server(self::HOST, self::PORT);
        $this->ws->set([
            'worker_num' => 2,
            'task_worker_num' => 2
            ]);
        $this->ws->on("open",[$this,"onOpen"]);
        $this->ws->on("message",[$this,"onMessage"]);
        $this->ws->on("task",[$this,"onTask"]);
        $this->ws->on("finish",[$this,"onFinish"]);
        $this->ws->on("close",[$this,"onClose"]);
        $this->ws->start();
    }

    /**
     * 监听ws连接事件
     *
     * @param $ws
     * @param $request
     */
    public function onOpen($ws,$request)
    {
        var_dump($request->fd);
        if ($request->fd == 1){
            swoole_timer_tick(2000,function ($timer_id){
                echo "2s:timerId:{$timer_id}" . PHP_EOL;
            });
        }
    }

    /**
     * 监听ws消息事件
     *
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame)
    {
//        echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
        echo "ser-push-message:{$frame->data}" . PHP_EOL;
        $data = [
          "task" => 1,
          "fd" => $frame->fd
        ];
//        $ws->task($data);
        swoole_timer_after(5000,function () use($ws,$frame){
            echo "5s-after" . PHP_EOL;
            $ws->push($frame->fd,"server-time-after:");
        });
        $ws->push($frame->fd, "server-push".date("Y-m-d H:i:s"));
    }


    /**
     * task任务自动会调
     *
     * @param $serv
     * @param $taskId
     * @param $workerId
     * @param $data
     * @return string
     */
    public function onTask($serv,$taskId,$workerId,$data)
    {
        print_r($data);
        sleep(10);
        return "on task finish"; //告诉worker
    }

    /**
     * 任务完成的时候调用
     *
     * @param $serv
     * @param $taskId
     * @param $data  onTask返回的值
     */
    public function onFinish($serv,$taskId,$data)
    {
        echo "taskId:{$taskId}" . PHP_EOL;
        echo "finish-data-success:{$data}" . PHP_EOL;
    }

    /**
     * close
     *
     * @param $ws
     * @param $fd
     */
    public function onClose($ws,$fd)
    {
        echo "clientid:{$fd}". PHP_EOL;
    }
}

$obj = new Ws();